package com.jcj.pojomessagepack;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;


/**
 * 客户端启动类
 */
public class AppClientPM {

    private final String host;
    private final int port;

    public AppClientPM(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 配置响应的参数,提供连接到远端的方法
     */
    public void run() throws Exception {
        //I/O线程池
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bs = new Bootstrap(); //客户端辅助启动类
            bs.group(group)
                    .channel(NioSocketChannel.class)  //实例化一个Channel
                    .remoteAddress(new InetSocketAddress(host, port)) //指定远端ip和端口
                    .handler(new InitializerClientPM());

            //连接到远程节点;等待连接完成
            ChannelFuture future = bs.connect().sync();

            //阻塞操作,closeFuture()开启了一个channel的监听器(这期间channel在进行各项工作),直到链路断开
            future.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully().sync();  //优雅的关闭资源
        }
    }

    public static void main(String[] args) throws Exception {

        new AppClientPM("127.0.0.1", 18081).run();
    }

}

























